package com.ruoyi.coffee.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.coffee.dto.LoginAppDto;
import com.ruoyi.coffee.utils.SecurityUtils;
import com.ruoyi.coffee.vo.AuthUser;
import com.ruoyi.coffee.domain.Users;
import com.ruoyi.coffee.dto.LoginDto;
import com.ruoyi.coffee.service.IUsersService;
import com.ruoyi.coffee.service.TokenService;
import com.ruoyi.coffee.utils.JsonUtils;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.bean.BeanUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

/**
 * @author dxj
 * @Description 微信用户接口
 * @date 2024/12/20 13:51
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
@AllArgsConstructor
@Api(tags = "微信用户接口")
public class WxMaUserController {
    private static final Logger logger = LoggerFactory.getLogger(WxMaUserController.class);
    private final WxMaService wxMaService;
    private IUsersService usersService;
    private TokenService tokenService;
    /**
     * 微信登陆接口
     */
    @PostMapping("/login")
    @ApiOperation(value = "微信用户登录", notes = "微信用户登录")
    public AjaxResult login(@RequestBody LoginDto loginDto) {
        logger.info("login接口入参{}", loginDto);
        if (StringUtils.isBlank(loginDto.getCode())) {
            return AjaxResult.error("empty jscode");
        }
        if (!wxMaService.switchover(loginDto.getAppid())) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", loginDto.getAppid()));
        }
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(loginDto.getCode());
            logger.info("sessionId,{}", session.getSessionKey());
            logger.info("openId,{}", session.getOpenid());
            // 用户信息校验
            if (!wxMaService.getUserService().checkUserInfo(session.getSessionKey(), loginDto.getRawData(), loginDto.getSignature())) {
                return AjaxResult.error("user check failed");
            }
            // 解密用户信息
            WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(session.getSessionKey(), loginDto.getEncryptedData(), loginDto.getIv());
            logger.info("userInfo,{}", userInfo);
            Users users = new Users();
            //通过openid查询用户信息,查询不到则新增用户
            Long count = usersService.count(new LambdaQueryWrapper<Users>().eq(Users::getOpenId, session.getOpenid()));
            if (count == 0) {
                users.setOpenId(session.getOpenid());
                users.setUsername(userInfo.getNickName());
                users.setNickname(userInfo.getNickName());
                users.setAvatarUrl(userInfo.getAvatarUrl());
                users.setPoints(0L);
                usersService.save(users);
            } else {
                users = usersService.getOne(new LambdaQueryWrapper<Users>().select(Users::getId, Users::getNickname, Users::getAvatarUrl).eq(Users::getOpenId, session.getOpenid()));
            }
            //构建AuthUser 对象
            AuthUser authUser = AuthUser.builder()
                    .id(users.getId())
                    .username(users.getNickname())
                    .nickName(users.getNickname())
                    .avatarUrl(users.getAvatarUrl())
                    .loginTime(System.currentTimeMillis())
                    .expireTime(System.currentTimeMillis() + 1000 * 60 * 60 * 24)
                    .build();
            //生成token
            String token = tokenService.createToken(authUser);
            return AjaxResult.success(token);
        } catch (WxErrorException e) {
            logger.error(e.getMessage(), e);
            return AjaxResult.error(e.toString());
        } finally {
            //清理ThreadLocal,防止内存泄漏
            WxMaConfigHolder.remove();
        }
    }

    /**
     * 获取用户信息
     *
     *
     * @return
     */
    @GetMapping("/getUserInfo")
    @ApiOperation(value = "获取用户信息", notes = "根据传入的id获取用户信息")
    public AjaxResult getUserInfo() {
       Long userId = SecurityUtils.getUserId();
        logger.info("getUserInfo接口入参{}", userId);
        Users users = usersService.selectUsersById(userId);
        AuthUser authUser=new AuthUser();
        BeanUtils.copyBeanProp(authUser,users);
        return AjaxResult.success(authUser);
    }


    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
//    @GetMapping("/info")
//    public String info(@PathVariable String appid, String sessionKey,
//                       String signature, String rawData, String encryptedData, String iv) {
//        if (!wxMaService.switchover(appid)) {
//            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
//        }
//
//        // 用户信息校验
//        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
//            WxMaConfigHolder.remove();//清理ThreadLocal
//            return "user check failed";
//        }
//
//        // 解密用户信息
//        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
//        WxMaConfigHolder.remove();//清理ThreadLocal
//        return JsonUtils.toJson(userInfo);
//    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
//    @GetMapping("/phone")
//    public String phone(@PathVariable String appid, String sessionKey, String signature,
//                        String rawData, String encryptedData, String iv) {
//        if (!wxMaService.switchover(appid)) {
//            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
//        }
//
//        // 用户信息校验
//        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
//            WxMaConfigHolder.remove();//清理ThreadLocal
//            return "user check failed";
//        }
//
//        // 解密
//        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
//        WxMaConfigHolder.remove();//清理ThreadLocal
//        return JsonUtils.toJson(phoneNoInfo);
//    }

    @PostMapping("/mbLogin")
    @ApiOperation(value = "App登录", notes = "App用户登录")
    public AjaxResult mbLogin(@RequestBody LoginAppDto loginAppDto) {
        logger.info("mbLogin{},Password", loginAppDto);
        Optional<AuthUser> authUser= usersService.mbLogin(loginAppDto.getUsername(),loginAppDto.getPassword());
        if (authUser != null) {
            //生成token
            String token = tokenService.createToken(authUser.get());
            return AjaxResult.success("success", token);
        } else {
            return AjaxResult.error("用户名或密码错误");
        }
    }

}
